package com.furkid.service.web;

import com.furkid.service.common.exception.BizException;
import com.furkid.service.common.exception.UnauthorizedException;
import com.furkid.service.constant.AjaxResult;
import com.furkid.service.constant.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(BizException.class)
    public AjaxResult handleBiz(BizException e) {
        return AjaxResult.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult handleAll(Exception e) {
        log.warn("exception: {}", e.getMessage());
        return AjaxResult.error(500, e.getMessage());
    }

    /**
     * 返回未授权异常
     * @param e 未授权异常
     * @return ResponseEntity<AjaxResult>
     */
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseEntity<AjaxResult> handleUnauthorized(UnauthorizedException e) {
        return ResponseEntity
                .status(HttpStatus.UNAUTHORIZED)
                .body(AjaxResult.error(HttpStatus.UNAUTHORIZED, e.getMessage()));
    }
}
